package com.youi.service.impl;

import com.google.common.collect.Maps;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.dao.PlamtwithdrawDao;
import com.youi.entity.Merchant;
import com.youi.entity.Orderprofitdetail;
import com.youi.entity.Plamtwithdraw;
import com.youi.entity.Plamtwithdrawdetail;
import com.youi.entity.Sysuser;
import com.youi.entity.Userorder;
import com.youi.entity.Userorderexcel;
import com.youi.entity.vo.ExportPlatformWithdrawVO;
import com.youi.manage.HttpSessionManage;
import com.youi.service.MerchantService;
import com.youi.service.OrderprofitdetailService;
import com.youi.service.PlamtwithdrawService;
import com.youi.service.PlamtwithdrawdetailService;
import com.youi.service.SetleaderlevelService;
import com.youi.service.SysuserService;
import com.youi.service.UserorderexcelService;
import com.youi.third.ali.oss.OSSUtil;
import com.youi.util.DateUtil;
import com.youi.util.FileUploadUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.SmsUtil;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PlamtwithdrawServiceImpl extends BaseServiceImpl<Plamtwithdraw> implements PlamtwithdrawService {

    private PlamtwithdrawDao plamtwithdrawDao;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private SetleaderlevelService setleaderlevelService;
    @Autowired
    private OrderprofitdetailService orderprofitdetailService;
    @Autowired
    private PlamtwithdrawdetailService plamtwithdrawdetailService;
    @Autowired
    private SysuserService sysuserService;
    @Autowired
    private UserorderexcelService userorderexcelService;


    @Autowired
    public void setfaultRecordDao(PlamtwithdrawDao plamtwithdrawDao) {
        this.plamtwithdrawDao = plamtwithdrawDao;
        super.setBaseDAO(plamtwithdrawDao);
    }

    @Override
    public void getWithdrawUserOrderMsg(List<Userorder> userOrderList) {
        if (CollectionUtils.isEmpty(userOrderList)) {
            return;
        }
        DecimalFormat amount = new DecimalFormat("0.00");
        //计算团长总分润比例
        Double leaderRatio = setleaderlevelService.getLeaderRate(1) + setleaderlevelService.getLeaderRate(2);
        for (Userorder userorder : userOrderList) {
            userorder.setLeaderRatio(leaderRatio);
            //获取平台和商家分润比例
            Map<String, Object> params = Maps.newHashMap();
            params.put(Common.DELSTATUS, DelStatus.NODEL);
            params.put("orderNo", userorder.getOrderNo());
            Orderprofitdetail orderprofitdetail = orderprofitdetailService.getByParam(params);
            Double leaderAmount = 0.00;
            if (orderprofitdetail != null) {
                userorder.setMerchantAmount(orderprofitdetail.getMerAmount());
                userorder.setPlatformAmount(orderprofitdetail.getPlatAmount());
                if (orderprofitdetail.getFirstAmount() != null && orderprofitdetail.getSecondAmount() != null) {
                    leaderAmount = orderprofitdetail.getFirstAmount() + orderprofitdetail.getSecondAmount();
                    userorder.setLeaderAmount(ObjectUtil.sciCal(leaderAmount, 2));
                } else if (orderprofitdetail.getFirstAmount() != null) {
                    leaderAmount = orderprofitdetail.getFirstAmount();
                    userorder.setLeaderAmount(ObjectUtil.sciCal(leaderAmount, 2));
                } else {
                    userorder.setLeaderAmount(ObjectUtil.sciCal(leaderAmount, 2));
                }
                //平台分账总额
//						Double platformSum=orderprofitdetail.getPlatAmount()+leaderAmount-orderprofitdetail.getServiceCharge();
                if (orderprofitdetail.getOrderAmount() == null || orderprofitdetail.getServiceCharge() == null || orderprofitdetail.getMerAmount() == null) {
                    System.out.println(orderprofitdetail.getOrderNo());
                }
                Double platformSum = orderprofitdetail.getOrderAmount() - orderprofitdetail.getServiceCharge() - orderprofitdetail.getMerAmount();
                userorder.setPlatformSum(ObjectUtil.sciCal(platformSum, 2));
                //获取手续费
                userorder.setServiceCharge(Double.valueOf(amount.format(orderprofitdetail.getServiceCharge())));
            }
            //获取供应商分润比例
            params = Maps.newHashMap();
            params.put(Common.DELSTATUS, DelStatus.NODEL);
            params.put(Common.ID, userorder.getMerchantId());
            Merchant merchant = merchantService.getByParam(params);
            Double merchantRatio = 85.00;
            if (merchant != null) {
                merchantRatio = 100.00 - merchant.getCommissionRatio();
                userorder.setMerchantRatio(merchantRatio);
            }
            Double platformRatio = 100.00 - merchantRatio - leaderRatio;
            userorder.setPlatformRatio(platformRatio);
        }
    }

    @Override
    public List<ExportPlatformWithdrawVO> listExportData(Map<String, Object> param) {
        List<ExportPlatformWithdrawVO> list = plamtwithdrawDao.listExportData(param);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        list.stream().forEach(withdraw -> {
            withdraw.setWithdrawType("易宝分账");
            withdraw.setStatusTxt(ObjectUtil.getPlatformApplyStatus(withdraw.getStatus()));
        });
        return list;
    }

    @Override
	@Deprecated
    public void toExcelPlatformUserorder(HttpServletRequest request, List<Userorder> userorderList) {
        // TODO Auto-generated method stub
        try {
            Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
            String fileName = "platformuserorder" + new Date().getTime() + "" + SmsUtil.getRandom(3) + ".xls";//文件名
            String fileUrl = FileUploadUtil.getUploadUrl(request, "filedownload" + File.separator + fileName);//生成路径
            WritableWorkbook workbook = Workbook.createWorkbook(new File(fileUrl));
            WritableSheet sheet1 = workbook.createSheet("Sheet1", 0);
            WritableFont font = new WritableFont(WritableFont.createFont("微软雅黑"), 10);
            WritableCellFormat format = new WritableCellFormat();
            format.setAlignment(Alignment.CENTRE);
            format.setVerticalAlignment(VerticalAlignment.CENTRE);
            Label label = new Label(0, 0, "主订单号", format);
            sheet1.addCell(label);
            label = new Label(1, 0, "子订单号", format);
            sheet1.addCell(label);
            label = new Label(2, 0, "订单金额", format);
            sheet1.addCell(label);
            label = new Label(3, 0, "手续费", format);
            sheet1.addCell(label);
            label = new Label(4, 0, "供应商分润金额", format);
            sheet1.addCell(label);
            label = new Label(5, 0, "供应商分润比例", format);
            sheet1.addCell(label);
            label = new Label(6, 0, "平台分润金额", format);
            sheet1.addCell(label);
            label = new Label(7, 0, "平台分润比例", format);
            sheet1.addCell(label);
            label = new Label(8, 0, "团长分润金额", format);
            sheet1.addCell(label);
            label = new Label(9, 0, "团长分润比例", format);
            sheet1.addCell(label);
            label = new Label(10, 0, "平台分账总额", format);
            sheet1.addCell(label);
            label = new Label(11, 0, "提现状态", format);
            sheet1.addCell(label);
            label = new Label(12, 0, "订单状态", format);
            sheet1.addCell(label);
            label = new Label(13, 0, "下单时间", format);
            sheet1.addCell(label);
            label = new Label(14, 0, "解冻时间", format);
            sheet1.addCell(label);
            label = new Label(15, 0, "确认收货时间", format);
            sheet1.addCell(label);
            label = new Label(16, 0, "平台提现成功时间", format);
            sheet1.addCell(label);
            Userorder userorder = null;
            for (int i = 0, j = 1; i < userorderList.size(); i++, j++) {
                userorder = userorderList.get(i);
                ObjectUtil.ToChangeNullToEmpty(userorder);
                label = new Label(0, j, userorder.getTopOrderNo(), format);
                sheet1.addCell(label);
                label = new Label(1, j, userorder.getOrderNo(), format);
                sheet1.addCell(label);
                label = new Label(2, j, userorder.getAmount().toString(), format);
                sheet1.addCell(label);
                if (userorder.getServiceCharge() != null) {
                    label = new Label(3, j, String.valueOf(userorder.getServiceCharge()), format);
                    sheet1.addCell(label);
                }
                label = new Label(4, j, String.valueOf(userorder.getMerchantAmount()), format);
                sheet1.addCell(label);
                label = new Label(5, j, String.valueOf(userorder.getMerchantRatio()), format);
                sheet1.addCell(label);
                label = new Label(6, j, String.valueOf(userorder.getPlatformAmount()), format);
                sheet1.addCell(label);
                label = new Label(7, j, String.valueOf(userorder.getPlatformRatio()), format);
                sheet1.addCell(label);
                label = new Label(8, j, String.valueOf(userorder.getLeaderAmount()), format);
                sheet1.addCell(label);
                label = new Label(9, j, String.valueOf(userorder.getLeaderRatio()), format);
                sheet1.addCell(label);
                label = new Label(10, j, String.valueOf(userorder.getPlatformSum()), format);
                sheet1.addCell(label);
                label = new Label(11, j, ObjectUtil.getMerchantStatus(userorder.getPlatformStatus()), format);
                sheet1.addCell(label);
                label = new Label(12, j, ObjectUtil.getOrderState(userorder.getStatus()), format);
                sheet1.addCell(label);
                label = new Label(13, j, DateUtil.simpdfyMdHms.format(userorder.getGmtOrder()), format);
                sheet1.addCell(label);
                if (userorder.getGmtUnfreeze() != null) {
                    label = new Label(14, j, DateUtil.simpdfyMdHms.format(userorder.getGmtUnfreeze()), format);
                    sheet1.addCell(label);
                }
                if (userorder.getGmtReceiving() != null) {
                    label = new Label(15, j, DateUtil.simpdfyMdHms.format(userorder.getGmtReceiving()), format);
                    sheet1.addCell(label);
                }
                if (userorder.getGmtPlatformWith() != null) {
                    label = new Label(16, j, DateUtil.simpdfyMdHms.format(userorder.getGmtPlatformWith()), format);
                    sheet1.addCell(label);
                }
            }
            workbook.write();
            workbook.close();
            InputStream inStream = new FileInputStream(fileUrl);
            byte[] data = ObjectUtil.readInputStream(inStream);
            String dowmupload = OSSUtil.upload(data, ".xls");
            if (dowmupload != null && dowmupload.length() > 0) {
                userorderexcelService.saveOrUpdate(new Userorderexcel(sysuser.getId(), 4, dowmupload));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WriteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
	@Deprecated
    public void toExcelPlamtwithdraw(HttpServletRequest request, List<Plamtwithdraw> plamtwithdrawList) {
        try {
            Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
            String fileName = "platformwithdraw" + new Date().getTime() + "" + SmsUtil.getRandom(3) + ".xls";//文件名
            String fileUrl = FileUploadUtil.getUploadUrl(request, "filedownload" + File.separator + fileName);//生成路径
            WritableWorkbook workbook = Workbook.createWorkbook(new File(fileUrl));
            WritableSheet sheet1 = workbook.createSheet("Sheet1", 0);
            WritableFont font = new WritableFont(WritableFont.createFont("微软雅黑"), 10);
            WritableCellFormat format = new WritableCellFormat();
            format.setAlignment(Alignment.CENTRE);
            format.setVerticalAlignment(VerticalAlignment.CENTRE);
            Label label = new Label(0, 0, "提现单号", format);
            sheet1.addCell(label);
            label = new Label(1, 0, "期号", format);
            sheet1.addCell(label);
            label = new Label(2, 0, "订单总金额", format);
            sheet1.addCell(label);
            label = new Label(3, 0, "手续费", format);
            sheet1.addCell(label);
            label = new Label(4, 0, "供应商总分润", format);
            sheet1.addCell(label);
            label = new Label(5, 0, "平台总分润", format);
            sheet1.addCell(label);
            label = new Label(6, 0, "团长总分润", format);
            sheet1.addCell(label);
            label = new Label(7, 0, "平台分润总值(平台+团长-手续费)", format);
            sheet1.addCell(label);
            label = new Label(8, 0, "提现方式", format);
            sheet1.addCell(label);
            label = new Label(9, 0, "审核状态", format);
            sheet1.addCell(label);
            label = new Label(10, 0, "审核人", format);
            sheet1.addCell(label);
            label = new Label(11, 0, "审核时间", format);
            sheet1.addCell(label);
            label = new Label(12, 0, "申请时间", format);
            sheet1.addCell(label);
            label = new Label(13, 0, "提现时间", format);
            sheet1.addCell(label);
            Plamtwithdraw plamtwithdraw = null;
            for (int i = 0, j = 1; i < plamtwithdrawList.size(); i++, j++) {
                plamtwithdraw = plamtwithdrawList.get(i);
                ObjectUtil.ToChangeNullToEmpty(plamtwithdraw);
                DecimalFormat dFormat = new DecimalFormat("0.00");
                label = new Label(0, j, plamtwithdraw.getWithdrawNo(), format);
                sheet1.addCell(label);
                label = new Label(1, j, plamtwithdraw.getDateNo(), format);
                sheet1.addCell(label);
                label = new Label(2, j, dFormat.format(plamtwithdraw.getOrderAmount()), format);
                sheet1.addCell(label);
                label = new Label(3, j, dFormat.format(plamtwithdraw.getServiceCharge()), format);
                sheet1.addCell(label);
                label = new Label(4, j, dFormat.format(plamtwithdraw.getMerchantAmount()), format);
                sheet1.addCell(label);
                label = new Label(5, j, dFormat.format(plamtwithdraw.getAllProfitAmount()), format);
                sheet1.addCell(label);
                label = new Label(6, j, dFormat.format(plamtwithdraw.getLeaderAmount()), format);
                sheet1.addCell(label);
                label = new Label(7, j, dFormat.format(plamtwithdraw.getRealProfitAmount()), format);
                sheet1.addCell(label);
                label = new Label(8, j, "易宝分账", format);
                sheet1.addCell(label);
                label = new Label(9, j, ObjectUtil.getPlatformApplyStatus(plamtwithdraw.getStatus()), format);
                sheet1.addCell(label);
                label = new Label(10, j, plamtwithdraw.getAuditorName(), format);
                sheet1.addCell(label);
                if (plamtwithdraw.getGmtApply() != null) {
                    label = new Label(11, j, DateUtil.simpdfyMdHms.format(plamtwithdraw.getGmtApply()), format);
                    sheet1.addCell(label);
                }
                label = new Label(12, j, DateUtil.simpdfyMdHms.format(plamtwithdraw.getGmtCreated()), format);
                sheet1.addCell(label);
                if (plamtwithdraw.getGmtWithdraw() != null) {
                    label = new Label(13, j, DateUtil.simpdfyMdHms.format(plamtwithdraw.getGmtWithdraw()), format);
                    sheet1.addCell(label);
                }
            }
            workbook.write();
            workbook.close();
            InputStream inStream = new FileInputStream(fileUrl);
            byte[] data = ObjectUtil.readInputStream(inStream);
            String dowmupload = OSSUtil.upload(data, ".xls");
            if (dowmupload != null && dowmupload.length() > 0) {
                userorderexcelService.saveOrUpdate(new Userorderexcel(sysuser.getId(), 5, dowmupload));
            }
        } catch (RowsExceededException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WriteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void getPlamtwithdraw(List<Plamtwithdraw> plamtWithdrawList) {
        if (CollectionUtils.isEmpty(plamtWithdrawList)) {
            return;
        }
        for (Plamtwithdraw plamtwithdraw : plamtWithdrawList) {
            getPlamtwithdraw(plamtwithdraw);
        }
    }

    @Override
    public void getPlamtwithdraw(Plamtwithdraw plamtwithdraw) {
        if (plamtwithdraw != null) {
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("plamtwithdrawId", plamtwithdraw.getId());
            List<Plamtwithdrawdetail> plamtwithdrawdetailList = plamtwithdrawdetailService.getByParams(prams);
            if (plamtwithdrawdetailList != null) {
                plamtwithdraw.setPlamtwithdrawdetailList(plamtwithdrawdetailList);
            }
            Sysuser sysuser = sysuserService.get(plamtwithdraw.getAuditorId());
            if (sysuser != null) {
                plamtwithdraw.setAuditorName(sysuser.getName());
            }
        }
    }
}